package com.kykj.kykjyzw.tool;
/**
 *
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
public class HTTPTool {//发起一个HTTP请求

    /**
     *
     * @param url 请求地址
     * @param param 传入参数
     * @param header 请求头
     * @return JSon格式的数据
     */

    public   String doGet(String url, Map<String, String>param,Map<String,String> header){
        String result="";//结果
        BufferedReader in = null;//读取输入流
        StringBuffer stringBuffer = new StringBuffer();
        String params="";//处理以后的参数
        try{
            //处理参数只有一个的情况
            if(param.size()==1){
                for(String parName: param.keySet()){
                    stringBuffer.append(parName).append("=").append(
                            java.net.URLEncoder.encode(param.get(parName),"UTF-8")
                    );
                }
                params=stringBuffer.toString();
            }else{//处理多个参数
                for(String parName: param.keySet()){
                    stringBuffer.append(parName).append("=").append(
                            java.net.URLEncoder.encode(param.get(parName),"UTF-8")
                    ).append("&");
                }
                //处理最后多的一个&符号
                String temp_par= stringBuffer.toString();
                params = temp_par.substring(0,temp_par.length()-1);//把最后一个&截取掉
            }
            String Full_Url=url+"?"+params;//最后组装完成的URL
            System.out.println(Full_Url);
            System.out.println(Full_Url);
            java.net.URL connURL= new java.net.URL(Full_Url);//创建一个URL对象
            java.net.HttpURLConnection httpURLConnection = (java.net.HttpURLConnection) connURL.openConnection();//打开一个请求
            //设置请求头
            if(header.size()!=0){
                for(String headName:header.keySet()){
                    httpURLConnection.addRequestProperty(headName,header.get(headName));//设置自定义请求头
                }
            }
            httpURLConnection.addRequestProperty("Accept","*/*");
            httpURLConnection.addRequestProperty("Connection","Keep-Alive");
            httpURLConnection.addRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpURLConnection.connect();//发起连接。
            //获取响应头部
            Map<String, List<String>> headMap=httpURLConnection.getHeaderFields();
            //遍历所有响应头字段
            for(String key:headMap.keySet()){
                System.out.println(key+","+headMap.get(key));
            }
            //获得输入流，设置编码格式并输出。
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
            //将得到的输入流，按格式输出并返回
            String line;
            while ((line=in.readLine())!=null){
                result = result + line;
            }
            System.out.println("Get调用成功!");
        }catch (Exception e){
            System.out.println("doGet错误"+e.getMessage());
        }finally {
            try{
                if(in != null){
                    in.close();
                }
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
        return result;
    }

    /**
     *
     * @param url 请求地址
     * @param param 传入参数
     * @param header 请求头
     * @return JSon格式的数据
     */
    public   String doPost(String url, Map<String, String>param,Map<String,String> header){
        String result="";
        BufferedReader in = null;//读取输入流
        StringBuffer stringBuffer = new StringBuffer();
        PrintWriter out = null;
        String params="";//处理以后的参数
        try{
            //处理参数只有一个的情况
            if(param.size()==1){
                for(String parName: param.keySet()){
                    stringBuffer.append(parName).append("=").append(
                            java.net.URLEncoder.encode(param.get(parName),"UTF-8")
                    );
                }
                params=stringBuffer.toString();
            }else{//处理多个参数
                for(String parName: param.keySet()){
                    stringBuffer.append(parName).append("=").append(
                            java.net.URLEncoder.encode(param.get(parName),"UTF-8")
                    ).append("&");
                }
                //处理最后多的一个&符号
                String temp_par= stringBuffer.toString();
                params = temp_par.substring(0,temp_par.length()-1);//把最后一个&截取掉
            }

            java.net.URL connURL= new java.net.URL(url);//创建一个URL对象
            java.net.HttpURLConnection httpURLConnection = (java.net.HttpURLConnection) connURL.openConnection();//打开一个请求
            //设置请求头
            if(header.size()!=0){
                for(String headName:header.keySet()){
                    httpURLConnection.addRequestProperty(headName,header.get(headName));//设置自定义请求头
                }
            }
            httpURLConnection.addRequestProperty("Accept","*/*");
            httpURLConnection.addRequestProperty("Connection","Keep-Alive");
            httpURLConnection.addRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

            //设置Post方法
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            out= new PrintWriter(httpURLConnection.getOutputStream());
            out.write(params);
            out.flush();

            //获得输入流，设置编码格式并输出。
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));
            //将得到的输入流，按格式输出并返回
            String line;
            while ((line=in.readLine())!=null){
                result = result + line;
            }
            System.out.println("Post调用成功!");
        }catch (Exception e){
            System.out.println("doPost错误"+ e.getMessage());
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (Exception e){
                System.out.println("关闭错误");
            }
        }
        return result;
    }
}
